//
//  NibLoadable.swift
//  FMUIKit
//
//  Created by Subo on 2018/2/13.
//  Copyright © 2018年 Followme. All rights reserved.
//

import Cocoa

public protocol NibLoadable: class {
    static var nibName: String { get }
}

public extension NibLoadable {
    static var nibName: String {
        return String(describing: self)
    }
}

public extension NibLoadable where Self: NSView  {
    
    static var nib: NSNib {
        guard let nib = NSNib(nibNamed: NSNib.Name(nibName), bundle: Bundle(for: self)) else {
            fatalError("nib file \(nibName) is not found.")
        }
        return nib
    }
    
    static func loadFromNib() -> Self {
        var topLevelObjects: NSArray?
        guard nib.instantiate(withOwner: self, topLevelObjects: &topLevelObjects) else {
            fatalError("Could not instantiate view from nib file \(nibName).")
        }
        
        guard let instance = topLevelObjects!.first(where: {$0 is Self}) as? Self else {
            fatalError("Could not instantiate view from nib file \(nibName).")
        }
        
        return instance
    }
}
